package protagonist.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    public static void main(String[] args) {
        String originalString = "lxl123456";

        // 加密原始字符串
        String encryptedString = encryptString(originalString);
        System.out.println("Encrypted String: " + encryptedString);

        // 模拟验证过程
        System.out.println("Is 'Hello, World!' valid? " + validateString(originalString, encryptedString));
        System.out.println("Is 'Hello, Java!' valid? " + validateString("Hello, Java!", encryptedString));
    }

    public static String encryptString(String input) {
        try {
            // 创建 MD5 消息摘要算法的实例
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 计算输入字符串的哈希值
            byte[] messageDigest = md.digest(input.getBytes());

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean validateString(String input, String encrypted) {
        // 对输入字符串进行加密，并与给定的加密字符串进行比较
        return encryptString(input).equals(encrypted);
    }
}
